<?php

namespace stlswm\WeChatMp\Auth;

use Exception;
use stlswm\WeChatMp\CurlHttp;
use stlswm\WeChatMp\MiniProgram;
use stlswm\WeChatMp\Response;

/**
 * Class Auth
 * @package stlswm\WeChatMp\Auth
 */
class Auth
{
    use CurlHttp;

    /**
     * @var MiniProgram
     */
    protected MiniProgram $miniProgram;

    /**
     * Auth constructor.
     * @param  MiniProgram  $miniProgram
     */
    public function __construct(MiniProgram $miniProgram)
    {
        $this->miniProgram = $miniProgram;
    }

    /**
     * 登录凭证校验
     * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
     * @param  string  $jsCode
     * @param  string  $grantType
     * @return Response
     * @throws Exception
     */
    public function code2Session(string $jsCode, string $grantType = 'authorization_code'): Response
    {
        $url = MiniProgram::$baseUri.'/sns/jscode2session?appid='.$this->miniProgram->getAppId().'&secret='.$this->miniProgram->getSecret()
            ."&js_code={$jsCode}&grant_type={$grantType}";
        return self::get($url);
    }

    /**
     * 获取小程序全局唯一后台接口调用凭据（access_token）
     * @return Response
     * @throws Exception
     */
    public function getAccessToken(): Response
    {
        $url = MiniProgram::$baseUri.'/cgi-bin/token?grant_type=client_credential&appid='.$this->miniProgram->getAppId().'&secret='.$this->miniProgram->getSecret();
        return self::get($url);
    }
}